package indi.readbook.example.gateway.utils.response;

import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class R extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    private Integer code;
    private String msg;
    private Object data;

    public R() {
        put("code", 200);
        put("msg", "操作成功");
    }

    public static R error() {
        return error(500, "操作失败");
    }

    public static R error(String msg) {
        return error(500, msg);
    }

    public static R noLogin() {
        R r = new R();
        r.put("code", 401);
        r.put("msg", "请登录后再次访问");
        return r;
    }

    public static R noLogin(String message) {
        R r = new R();
        r.put("code", 401);
        r.put("msg", message);
        return r;
    }

    public static R error(int code, String msg) {
        R r = new R();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    public static R ok(String msg) {
        R r = new R();
        r.put("msg", msg);
        return r;
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R ok() {
        return new R();
    }

    public static R opertionListResponse(List list) {
        R r = new R();
        if (CollectionUtils.isEmpty(list)) {
            return error("暂无数据");
        } else {
            return ok("查询成功")
                    .put("data", list);
        }
    }

    public static <T> R opertionPojoResponse(T t) {
        R r = new R();
        if (t == null) {
            return error("暂无数据");
        } else {
            return ok("查询成功")
                    .put("data", t);
        }
    }

    public static R insertOrUpdateResponse(Boolean result) {
        if (result) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public static boolean isOk(R r) {
        if (r.getOrDefault("code", 0).equals("1")) {
            return true;
        } else {
            return false;
        }
    }
}
